package com.sumainfor.pc.gmio.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.ParentDeptVo;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.DiComplaintMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.gmio.feign.ZuulFeign.ZuulFeign;
import com.sumainfor.pc.gmio.service.DiComplaintService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 */
@Service
public class DiComplaintSerivceImpl implements DiComplaintService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(DiComplaintSerivceImpl.class);
    @Autowired
    private DiComplaintMapper diComplaintMapper;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private ZpcMktFeign zpcMktFeign;

    @Autowired
    ZuulFeign ZuulFeign;

    @Autowired
    ZzuulFeign ZzuulFeign;

    String UUID = null;

    @Autowired
    private ZzuulFeign zzuulFeign;

    /**
     * 查询客户投诉列表 待处理
     */
    @Override
    public List<Map<String, Object>> getDiComplaintListd(Map<String, Object> params) {
        List<Map<String, Object>> list = diComplaintMapper.getDiComplaintListd(params);
        //去市场部查询租客的信息
        params.put("tenBillList", list);
        JsonResult result = zpcMktFeign.getTenSysUserInfoListForGmio(params);
        if (result.get("errorCode").equals("0")) {
            List<Map<String, Object>> mList = (List<Map<String, Object>>) result.get("result");
            System.out.println("result:" + result);
            return mList;
        }
        return list;
    }

    /**
     * 查询客户投诉列表总数 待处理
     */
    @Override
    public Integer getDiComplaintCountListd(Map<String, Object> params) {
        return diComplaintMapper.getDiComplaintCountListd(params);
    }

    /**
     * 查询客户投诉列表 已处理
     */
    @Override
    public List<Map<String, Object>> getDiComplaintListy(Map<String, Object> params) {
        List<Map<String, Object>> list = diComplaintMapper.getDiComplaintListy(params);
        //去市场部查询租客的信息
        params.put("tenBillList", list);
        JsonResult result = zpcMktFeign.getTenSysUserInfoListForGmio(params);
        if (result.get("errorCode").equals("0")) {
            List<Map<String, Object>> mList = (List<Map<String, Object>>) result.get("result");
            System.out.println("result:" + result);
            return mList;
        }
        return list;
    }

    /**
     * 查询客户投诉列表总数 已处理
     */
    @Override
    public Integer getDiComplaintCountListy(Map<String, Object> params) {
        return diComplaintMapper.getDiComplaintCountListy(params);
    }

    /**
     * 根据投诉编号查询投诉详情
     */
    public Map<String, Object> getDiComplaintInfo(Map<String, Object> params) {
        return diComplaintMapper.getDiComplaintInfo(params);
    }

    /**
     * 租后主管提交投诉解决方案
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updateDiComplaint(Map<String, Object> params) {
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                params.put("Status", 2);
                params.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                params.put("DbackTime", params.get("updtm"));
                diComplaintMapper.updateDiComplaint(params);
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return diComplaintMapper.updateDiComplaint(params);
    }

    /**
     * 租后主管发起投诉
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addDiComplaint(Map<String, Object> params) {
        Integer count = 0;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                //获取当前操作人的服务中心编号
                SysUserVo userVo = ContextUtils.getSysUser();
                ParentDeptVo vo = null;
                for (int i = 0; i < userVo.getLength(); i++) {
                    ParentDeptVo vo1 = userVo.getParentDeptVo();
                    if (vo1.getType().equals(3)) {
                        vo = vo1;
                        break;
                    }
                }
                //投诉编号
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "CompId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_complaint");
                }});
                System.out.println("uuid:" + uuid);
                if (uuid != null && (!uuid.get("uuid").toString().equals(""))) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("co", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("co", 0);
                }
                if (vo != null) {
                    params.put("MiId", vo.getDeptId());//服务中心编号
                }
                params.put("InsId", ContextUtils.getUserId());//发起操作人编号（租客自己发起没有该编号）
                params.put("CompId", UUID);//投诉编号
                params.put("IfHelp", 1);//租后主管吧帮忙投诉 0.否  1.是
                params.put("Status", 1);//投诉状态  1.待处理 2.已处理
                params.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                System.out.println("params1:" + params);
                params.put("CompTime", params.get("instm"));
                System.out.println("params2:" + params);
                count = diComplaintMapper.addDiComplaint(params);
                if (count > 0) {
                    sendMessage();
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return count;
    }


    private void sendMessage() {
        String uid;
        try {
            uid = ContextUtils.getUserId();
        } catch (Exception e) {
            try {
                uid = ContextUtils.getWxInfo().getTenId();
            } catch (Exception ex) {
                uid = "";
            }
        }
        //通知
        CustomMap data = CustomMap.create("MeType", 13)
                .put("Title", "客投中心")
                .put("Content", HtmlUtil.stringToHTML("注意！有新的投诉订单待处理 请及时处理！", "", Color.blue))
                .put("by", uid)
                .put("term", 3);
        zzuulFeign.AddMessage(data);
    }

    /**
     * 功能描述:
     * 租客端发起投诉
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/5/11 10:46
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean AddTenantComplaint(Map<String, Object> params) {
        boolean result = false;
        lock.lock();
        try {
            try {
                //投诉编号
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "CompId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_complaint");
                }});
                System.out.println("uuid:" + uuid);
                if (uuid != null && (!uuid.get("uuid").toString().equals(""))) {
                    int number = Integer.valueOf(uuid.get("uuid").toString());
                    UUID = ComUtils.getLocalTrmSeqNum("co", number);
                } else {
                    UUID = ComUtils.getLocalTrmSeqNum("co", 0);
                }
                //所有新增处理
                Map<String, Object> commonInsertParms = new HashMap<String, Object>();
                commonInsertParms.put("CompId", UUID);//投诉编号
                commonInsertParms.put("Status", 1);//投诉状态  1.待处理 2.已处理
                commonInsertParms.put("term", "1");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                commonInsertParms.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(commonInsertParms);
                params.putAll(commonInsertParms);
                params.put("CompTime", ConvertDateTime.getCurrentTime());
                //投诉照片
                String CompFile = null;
                StringBuffer stringBuffer = new StringBuffer();
                List<String> CompFilelist = (List<String>) params.get("CompFile");
                if (CompFilelist.size() > 0) {
                    for (String str : CompFilelist) {
                        stringBuffer.append(str).append(",");
                    }
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    CompFile = stringBuffer.toString();
                }
                params.put("CompFile", CompFile);
                //租客发起投诉
                Integer row = diComplaintMapper.addDiComplaint(params);
                if (row > 0) {
                    sendMessage();
                    //客投中心通知
                    CustomMap data = CustomMap.create("MeType", 11)
                            .put("Title", "客投中心")
                            .put("Content", HtmlUtil.stringToHTML("注意！有新的投诉订单待处理 请及时处理！", "", Color.blue))
                            .put("term", 1);
                    ZzuulFeign.AddMessage(data);
                    result = true;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }
}
